<template>
  <div class="Login">
    <Header :zIndex="7" ref="Header"></Header>
    <div class="login main-box">
      <div class="login-warp">
        <div class="right">
          <img src="../assets/img/loginBg.png" alt="">
        </div>
        <div class="left">
          <div class="login-content login-content-lpoll">
            <div class="pc-login">
              <ul class="tabs">
                <li :class="loginIndex == 1 ? 'active' : ''" @click="loginChange(1)">用户登录</li>
                <li :class="loginIndex == 2 ? 'active' : ''" @click="loginChange(2)">用户注册</li>
              </ul>
              <!-- 登录表单 -->
              <div class="passwordLogin loginDiv" v-if="loginIndex == 1">
                <el-form ref="form1" :rules="rules1" @submit.native.prevent :model="form1">
                  <el-form-item prop="name">
                    <el-input class="username" placeholder="请输入手机号/用户名" v-model="form1.name" autocomplete="off" maxlength="20" clearable>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="password">
                    <el-input class="pass" placeholder="请输入密码" v-model="form1.password" autocomplete="off" minlength="6" maxlength="20" show-password clearable>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <el-row>
                      <el-col :span="12">
                        <el-input v-model="form1.code" maxlength="6" placeholder="请输入图形验证码"></el-input>
                      </el-col>
                      <el-col :span="1"> &nbsp; </el-col>
                      <el-col :span="11">
                        <img :src="authUrl" class="authcode" title="点击刷新" @click="refresh" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" native-type="submit" @click="loginUser" class="okbtn">登录</el-button>
                    <el-button type="text" style="margin-top:10px;" @click="showResetDialog" size="medium" icon="el-icon-question">忘记密码</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 用户注册表单 -->
              <div class="passwordLogin registDiv" v-if="loginIndex == 2">
                <el-form ref="form2" :rules="rules2" :model="form2">
                  <el-form-item prop="name">
                    <el-input class="username" placeholder="请输入手机号/用户名" v-model="form2.name" autocomplete="off" clearable>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="password">
                    <el-input class="pass" placeholder="请输入密码" v-model="form2.password" autocomplete="off" show-password clearable>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <el-row>
                      <el-col :span="12">
                        <el-input v-model="form2.code" maxlength="6" placeholder="请输入短信验证码"></el-input>
                      </el-col>
                      <el-col :span="1"> &nbsp; </el-col>
                      <el-col :span="11">
                        <el-button size="small" @click="confirmAuth(1)" :disabled="disableSms">{{smstips}}</el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-row class="el-form-item">
                    <el-button type="primary" @click="registUser" class="okbtn" :disabled="!read1">立即注册</el-button>
                  </el-row>
                  <el-form-item>
                    <el-checkbox :label="true" v-model="read1">我已阅读并同意《<a href="/Helper?id=14" style="color:#409EFF" target="_blank">用户注册协议</a>》</el-checkbox>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="showResetDlg" width="340px" top="30vh" :close-on-press-escape="false" :close-on-click-modal="false">
      <template slot="title">
        <h3 style="color:#000;text-align:center">重置密码</h3>
      </template>
      <div class="reset">
        <el-input v-model="resetdata.phone" prefix-icon="el-icon-s-custom" type="tel" maxlength="11" name="phone" placeholder="请输入手机号码"></el-input>
        <el-row>
          <el-col :span="13">
            <el-input v-model="resetdata.code" prefix-icon="el-icon-postcard" name="code" maxlength="6" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="2">&nbsp;</el-col>
          <el-col :span="9">
            <el-button @click="confirmAuth(2)" :disabled="disableSms">{{smstips}}</el-button>
          </el-col>
        </el-row>
        <el-input v-model="resetdata.password" type="password" maxlength="20" prefix-icon="el-icon-lock" placeholder="请输入新密码"></el-input>
        <el-button type="primary" style="width:100%" @click="resetPwd">确认重置</el-button>
        <el-button type="text" @click="showResetDlg=false">想起来了，马上登录</el-button>
      </div>
    </el-dialog>
    <el-dialog title="发送短信验证" width="340px" top="35vh" :visible.sync="dialogVisible">
      <el-row>
        <el-col :span="11">
          <el-input v-model="smsauth" maxlength="6" placeholder="请输入图形验证码"></el-input>
        </el-col>
        <el-col :span='1'> &nbsp; </el-col>
        <el-col :span='12'>
          <img :src="smsAuthUrl" height="30px" alt='点击刷新' @click="refreshSmsAuth" />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" style="width:40%" @click="sendSms">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import User from '../../utils/user'
import Ajax from '../../utils/ajax'
import Header from '../components/Header.vue'
import { Toast } from 'vant'

export default {
  name: 'Login',
  components: {
    Header
  },
  data() {
    return {
      activeName: 'first',
      authUrl: '',
      smsAuthUrl: '',
      smsType: 1,
      smstips: '获取验证码',
      smstips2: '获取验证码',
      smsdelay: 60,
      disableSms: false,
      disableSms2: false,
      dialogVisible: false,
      showResetDlg: false,
      redirect: '',
      smsauth: '',
      resetdata: {
        phone: '',
        code: '',
        password: ''
      },
      read1: true,
      form1: {
        name: '',
        password: '',
        code: ''
      },
      form2: {
        name: '',
        password: '',
        code: '',
        referral: ''
      },
      loginIndex: 1,
      rules1: {
        name: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }]
      },
      rules2: {
        name: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.$route && this.$route.query) {
      var query = this.$route.query
      if (query.reg == '1') {
        this.loginChange(2)
      }
      if (query.spid) {
        this.form2.referral = query.spid
      }
      if (query.redirect) {
        this.redirect = query.redirect
      }
      if (query.access_token) {
        this.tokenLogin(query.access_token)
      }
    }
    if (!this.redirect || this.redirect == '') this.redirect = '/Manage'
    if (User.getToken() && User.getInfo()) {
      this.$router.replace(this.redirect)
      return
    }
    this.setTitle('会员登录')
    this.refresh()
  },
  methods: {
    // 发送请求获取验证码图
    refresh() {
      this.authUrl = Ajax.serverUrl + '/common/captcha?_=' + Math.random()
    },
    refreshSmsAuth() {
      this.smsAuthUrl = Ajax.serverUrl + '/common/captcha?_=' + Math.random()
    },
    showResetDialog() {
      this.resetdata = { phone: '', code: '', password: '' }
      this.showResetDlg = true
    },
    loginChange(e) {
      if (this.loginIndex == e) return

      this.loginIndex = e

      if (e == 1) {
        this.setTitle('会员登录')
        this.refresh()
      } else {
        this.setTitle('会员注册')
      }

      this.$nextTick(() => {
        this.$refs['form' + e].fields.forEach((el) => {
          el.resetField()
        })
      })
    },
    confirmAuth(n) {
      this.smsType = n
      var reg = /^1[3|4|5|6|7|8|9]\d{9}$/g
      if (n == 1) {
        if (!this.form2.name || !reg.test(this.form2.name)) {
          this.$alert('请输入正确的手机号')
          return
        }
      } else if (n == 2) {
        if (!this.resetdata.phone || !reg.test(this.resetdata.phone)) {
          this.$alert('请输入正确的手机号')
          return
        }
      }
      this.smsauth = ''
      this.refreshSmsAuth()
      this.dialogVisible = true
    },
    countDown(that) {
      if (that.smsdelay > 0) {
        if (that.smsType == 1) {
          that.disableSms = true
          that.smstips = this.smsdelay + '秒后重发'
        } else {
          that.disableSms2 = true
          that.smstips2 = this.smsdelay + '秒后重发'
        }

        setTimeout(that.countDown, 1000, that)
      } else {
        if (that.smsType == 1) {
          that.disableSms = false
          that.smstips = '获取验证码'
        } else {
          that.disableSms2 = false
          that.smstips2 = '获取验证码'
        }
      }
      that.$forceUpdate()
      that.smsdelay--
    },
    sendSms() {
      if (!this.smsauth || this.smsauth.length < 6) {
        this.$alert('请输入图形验证码')
        return
      }
      var phone = this.form2.name
      if (this.smsType == 2) {
        phone = this.resetdata.phone
      }
      Ajax.post('common/sendsms', {
        type: this.smsType,
        phone: phone,
        code: this.smsauth
      })
        .then((res) => {
          if (res.code == 0) {
            this.dialogVisible = false
            if (this.smsType == 1) {
              this.disableSms = true
            } else {
              this.disableSms2 = true
            }
            this.$message({
              message: '短信发送成功',
              type: 'success'
            })
            this.$forceUpdate()
            this.smsdelay = 60
            this.countDown(this)
          } else {
            this.dialogVisible = false
            this.$alert('短信发送失败:' + res.msg, { type: 'error' })
          }
        })
        .catch((err) => {
          console.error(err)
          this.dialogVisible = false
          this.$alert('短信发送失败', { type: 'error' })
        })
    },
    tokenLogin(token) {
      if (token) {
        const that = this
        Ajax.get('member/token/login?token=' + encodeURIComponent(token))
          .then((res) => {
            if (res.code == 0) {
              User.saveInfo(res.data.userInfo)
              User.saveToken(res.data.token)
              Toast('登录成功')
              setTimeout(() => {
                that.$router.replace(this.redirect)
              }, 1000)
            } else {
              this.$alert('登录失败：' + res.msg, { type: 'error' })
            }
          })
          .catch((err) => {
            console.error(err)
            this.$alert('登录失败，网络错误', { type: 'error' })
          })
      }
    },
    loginUser() {
      const that = this
      this.$refs.form1.validate((valid) => {
        if (valid) {
          Ajax.post('member/login', this.form1).then((data) => {
            if (data.code === 0) {
              User.saveToken(data.data.token)
              User.saveInfo(data.data.userInfo)
              Toast('登录成功')
              setTimeout(() => {
                that.$router.replace(this.redirect)
              }, 1000)
            } else {
              this.refresh()
              this.$alert(data.msg)
            }
          })
        }
      })
    },
    registUser() {
      const that = this
      if (!this.read1) {
        this.$alert('请先阅读并同意《用户注册协议》', { type: 'warning' })
        return
      }
      this.$refs.form2.validate((valid) => {
        if (valid) {
          var src = User.getRef()
          if (src) {
            this.form2.source = src
          }

          Ajax.post('member/register', this.form2).then((data) => {
            if (data.code == 0) {
              this.$alert('注册成功', { type: 'success' })
              User.saveToken(data.data.token)
              User.saveInfo(data.data.userInfo)
              setTimeout(() => {
                that.$router.replace(this.redirect)
              }, 1000)
            } else {
              this.$alert(data.msg, { type: 'error' })
            }
          })
        }
      })
    },
    resetPwd() {
      var reg = /^1[3|4|5|6|7|8|9]\d{9}$/g
      if (!this.resetdata.phone || !reg.test(this.resetdata.phone)) {
        this.$alert('请输入正确的手机号')
        return
      }
      if (!this.resetdata.code || this.resetdata.code.length < 4) {
        this.$alert('请输入手机验证码')
        return
      }
      if (!this.resetdata.password || this.resetdata.password.length < 6) {
        this.$alert('新密码至少要求由英文6个字符组成')
        return
      }
      Ajax.post('member/reset', this.resetdata)
        .then((res) => {
          if (res.code == 0) {
            this.$alert('密码重置成功！', { type: 'success' })
            this.showResetDlg = false
          } else {
            this.$alert('密码重置失败，' + res.msg, { type: 'error' })
          }
        })
        .catch((err) => {
          this.$alert('密码重置失败，网络错误', { type: 'error' })
        })
    }
  }
}
</script>
<style src="@/assets/css/login.css"  scoped></style>
